package com.qili.controller.supervisor;

import com.qili.util.DateUtil;
import com.spire.doc.Document;
import com.spire.doc.*;
import com.spire.doc.documents.BookmarksNavigator;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextBodyPart;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/1/7
 * @description
 */
public class T2 {

    public static void main(String[] args) {
        try {
            /*文字替换成书签*/
            String url="D:/tt/ceshi.doc";
            String imageurl="D:\\tt\\101.jpg";
            String lebel="PO";
            String text="盖章";
            //addStampImage(url, url, imageurl,"盖章","监理单位");
            mergeWord(url,"D:/tt/jfsq.docx");

        } catch (Exception e) {

        }


    }

    public static void mergeWord(String targetWordPath, String copyWordPath) throws Exception {
        try {
            //targetWordPath文档
            Document targetword = new Document(targetWordPath);
            //copyWordPath插入到targetWordPath文档
            targetword.insertTextFromFile(copyWordPath, FileFormat.Docx_2013);
            //保存合并后的文档
            targetword.saveToFile(targetWordPath, FileFormat.Docx_2013);
            InputStream is = new FileInputStream(targetWordPath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetWordPath);
            document.write(os);
            System.out.println("生成docx文档成功！");
            openWord(targetWordPath);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new Exception("合并文档出错：" + e.getMessage());
        }

    }

    public static void openWord(String filepath) {
        final Runtime runtime = Runtime.getRuntime();
        Process process = null;
        final String cmd = "rundll32 url.dll FileProtocolHandler file://" + filepath + "";//要打开的文件路径。
        try {
            process = runtime.exec(cmd);
        } catch (final Exception e) {
            System.out.println("Error exec!");
        }
    }

    public static void ss() {
        //实例化Document类的对象，并加载测试文档
        try {
            Document doc = new Document();
            doc.loadFromFile("D:\\tt\\2.doc");
            //加载替换的图片
            /*   Image image=Image.FromFile("g.png");*/
            Image image = ImageIO.read(new FileInputStream("D:\\tt\\101.jpg"));
            //获取第一个section
            Section sec = doc.getSections().get(0);
            //查找文档中的指定文本内容
            TextSelection[] selections = doc.findAllString("日期", true, true);
            int index = 0;
            TextRange range = null;
//遍历文档，移除文本内容，插入图片
            for (TextSelection selection : selections) {
                DocPicture pic = new DocPicture(doc);
                pic.loadImage(new FileInputStream("D:\\tt\\101.jpg"));
                pic.setWidth(50f);
                pic.setHeight(50f);
                range = selection.getAsOneRange();
                Paragraph para = range.getOwnerParagraph();
                index = para.getChildObjects().indexOf(range);
                //添加书签

                BookmarkStart start = new BookmarkStart(doc, "书签1");

                BookmarkEnd end = new BookmarkEnd(doc, "书签1");

                para.getChildObjects().insert(index, start);

                para.getChildObjects().insert(index + 2, end);


        /*        para.getChildObjects().insert(index,pic);
                para.getChildObjects().remove(range);*/
            }
            //保存文档
            doc.saveToFile("D:\\tt\\2.doc", FileFormat.Docx_2010);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //文字位置添加书签
    public static void insertLeble(String filePath, String text, String leble) {
        Document doc = new Document();

        InputStream is = null;
        OutputStream os = null;
        try {
            doc.loadFromFile(filePath);
            //查找文档中的指定文本内容
            TextSelection[] selections = doc.findAllString(text, true, true);
            int index = 0;
            TextRange range = null;
            //遍历文档，移除文本内容，插入图片
            for (TextSelection selection : selections) {
                range = selection.getAsOneRange();
                Paragraph para = range.getOwnerParagraph();
                System.out.println(range.getText()+"kkkkkkkkkkkkkk");
                index = para.getChildObjects().indexOf(range);
                //添加书签
                BookmarkStart start = new BookmarkStart(doc, leble);
                BookmarkEnd end = new BookmarkEnd(doc, leble);
                para.getChildObjects().insert(index + 0, start);
                para.getChildObjects().insert(index + 1, end);
            }
            //保存文档
            doc.saveToFile(filePath,FileFormat.Docx_2013);
            doc.dispose();

            doc.dispose();
            /*os.close();
            is.close();*/
            // os.close();
            System.out.println("文字位置添加书签成功");
        } catch (Exception e) {
            System.out.println("文字位置添加书签出错：" + e.getMessage());
            e.printStackTrace();
        } finally {
            doc.dispose();
        }

    }

    //文字替换标签
    public static String ReplaceBookmarkContentWithNewContent(String filePath, String docUrl, Map<String, String> con) {
        //创建文档对象
        Document doc = new Document();
        //加载包含书签的Word文档
        doc.loadFromFile(docUrl);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(new Date());
        String docInfo = filePath + "/" + nowDate + ".docx";
        Iterator iter = con.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String lable = entry.getKey().toString();
            String content = entry.getValue().toString();
            //定位到指定书签位置
            BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
            bookmarksNavigator.moveToBookmark(lable);
            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
            bookmarksNavigator.replaceBookmarkContent(content, true);
        }
        //保存文档
        doc.saveToFile(filePath);

        doc.dispose();
        return docInfo;


    }



    //图片替换文档内标签
    public static void replaceBookmarkWithImg(String filePath, String docUrl, Map<String, String> con) {
        //加载包含书签的文档
        Document doc = new Document();
        InputStream is = null;
        OutputStream os = null;
        try {
            doc.loadFromFile(docUrl);
            Iterator iter = con.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String lable = entry.getKey().toString();
                String content = entry.getValue().toString();
                //定位到指定书签位置
                BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
                bookmarksNavigator.moveToBookmark(lable, true, true);
                //添加图片，替换原有书签内容
                Paragraph para = new Paragraph(doc);
                DocPicture pic2 = para.appendPicture(content);
                pic2.setHeight(100f);
                pic2.setWidth(100f);
                TextBodyPart bodyPart = new TextBodyPart(doc);
                bodyPart.getBodyItems().add(para);
                bookmarksNavigator.replaceBookmarkContent(bodyPart);
            }
            //保存doc文档
            doc.saveToFile(filePath, FileFormat.Docx_2013);


            is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            os = new FileOutputStream(filePath);
            document.write(os);
            doc.dispose();
            os.close();
            is.close();
            System.out.println("插入图片成功");
        } catch (Exception e) {
            System.out.println("插入图片出错：" + e.getMessage());
            e.printStackTrace();
        } finally {
            doc.dispose();
        }
    }

/*  public static void main(String[] args) throws FileNotFoundException {
        String url="D:\\template\\doc\\工程变更单模板11.docx";
        List<String> list=new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            int y=i+1;
            list.add("PO_F"+y);
        }
          Map map= getTextByLebel(url,list);
         System.out.println(map);

    }*/

    public static Map getTextByLebel(String url, List<String> list) {
        Map map = new HashMap();
        Document doc = new Document();
        //加载Word文档
        doc.loadFromFile(url);
        for (int i = 0; i < list.size(); i++) {
            //获取指定书签
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            /*获取书签*/
            String lebel = list.get(i);
            navigator.moveToBookmark(lebel);
            //获取书签内容
            TextBodyPart textBodyPart = navigator.getBookmarkContent();
            //创建String变量
            String text = "";
            //遍历书签内容的项目
            for (Object item : textBodyPart.getBodyItems()) {
                //判断项目是否为段落
                if (item instanceof Paragraph) {
                    Paragraph paragraph = (Paragraph) item;
                    //遍历段落中的子对象
                    for (Object childObj : paragraph.getChildObjects()) {
                        //判断子对象是否为TextRange
                        if (childObj instanceof TextRange) {
                            //获取TextRange中的文本
                            TextRange textRange = (TextRange) childObj;
                            text = text + textRange.getText();
                        }
                    }
                }
            }
            //将获取到的文本写入Txt文件
            System.out.println(text);
            if ("PO_F1".equals(lebel)) {
                String textnew = text.replaceAll("由于", "").replaceAll("原因", "").replaceAll("_", "");
                map.put("reason", textnew);
            } else if ("PO_F2".equals(lebel)) {
                String textnew = text.replaceAll("兹提出", "").replaceAll("产品名称", "").replaceAll("_", "");
                map.put("name", textnew);
            } else if ("PO_F3".equals(lebel)) {
                String textnew = text.replaceAll("由", "").replaceAll("变更", "").replaceAll("_", "");
                map.put("after", textnew);
            } else if ("PO_F4".equals(lebel)) {
                String textnew = text.replaceAll("为", "").replaceAll("的工程变更", "").replaceAll("_", "");
                map.put("before", textnew);
            } else if ("PO_F5".equals(lebel)) {
                String textnew = text.replaceAll("变更金额为", "").replaceAll("（内容见附件）", "").replaceAll("_", "");
                map.put("money", textnew);
            }
        }
        return map;
    }

    /**
     * @param sourceFile
     * @param targetFile
     * @Author:zhaoyongke
     * @Description:  签章
     * @Date:15:33 2021/1/10
     */
    public static void addStampImage(String sourceFile, String targetFile, String imageurl, String keyword,String  contenttext)  throws  Exception {
        try {
            Document doc1 = new Document();
            doc1.loadFromFile(sourceFile);
            doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
            XWPFDocument doc;
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {//遍历每一个单元格
                        if (cell.getText().contains(contenttext)) {//如果遇到"&章"则进行替换
                            try {
                                insertCellStamp(cell, imageurl,keyword, contenttext);//给带有要盖章字样的单元格 加上章的图片
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            InputStream is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            doc1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void insertCellStamp(XWPFTableCell cell, String imageurl,String keyword ,String contenttext) {//给带有要盖章字样的单元格 加上章的图片
        for (XWPFParagraph para : cell.getParagraphs()) {
            //插入图片
            for (int i = 0;  i < para.getRuns().size(); i++) {
                try {
                    XWPFRun run = para.getRuns().get(i);
                    String text = run.text()+"";
                    System.out.println(text+"PPPPPPPPPPPPPP");
                    if (text.contains(keyword)) {
                        /*删除盖章关键字*/
                        run.setText(text.replace(keyword,""), 0);
                        String imgFile = imageurl;
                        System.out.println("插入盖章图片:" + imgFile);
                        FileInputStream is = new FileInputStream(imgFile);
                        run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(100), Units.toEMU(100)); // 100x100 pixels
                        is.close();
                    }
                    if(text.indexOf("年")!=-1){
                        String newtext=text.substring(0,text.indexOf("年"))+ DateUtil.formatDate(new  Date(),"yyyy年MM月dd日");
                        run.setText(newtext, 0);
                    }


                } catch (Exception e) {
                    System.out.println("Error: ========  插入单个公章图片时出错了:可能是图片路径不存在。不影响主流程");
                    e.printStackTrace();
                }
            }
        }
    }
}








